# from flask import Flask, request, jsonify, Response
from flask import Flask, request, jsonify

app = Flask(__name__)


# 交互因素问题描述
def interation_problem_analysis(interaction_all_attr_datas):
    if interaction_all_attr_datas is None:
        return []

    pageVisitId = 1
    elementClickId = 2

    # 页面访问错误
    visit_page_err_count = 0
    # 空白页
    is_blank_page_count = 0
    # 点击事件报错
    element_click_err_count = 0
    # 重复点击
    repeat_click_count = 0
    # 网页跳转
    time_since_page_load_dire = {
        'last_timeSincePageLoad': 0,
        'low_count': 0
    }

    # 扣分因素
    penalty_reason = []
    # 记录交互错误因素
    for i_dire in interaction_all_attr_datas:
        event_id = i_dire.get('event_id')  # 事件类型id
        interaction_attr = i_dire.get('interaction_attr')  # 交互属性

        # 页面跳转
        time_since_page_load = interaction_attr.get('timeSincePageLoad')
        if time_since_page_load and time_since_page_load['value'] > 0:
            time_val = time_since_page_load['value']
            last_time = time_since_page_load_dire.get('last_timeSincePageLoad')
            len_time_apart = time_val - last_time
            # 页面跳转时长超过1800ms视为加载慢
            if last_time != 0 and len_time_apart > 1800:
                time_since_page_load_dire['low_count'] += time_since_page_load_dire.get('low_count')
                time_since_page_load_dire['last_timeSincePageLoad'] = time_val

        # 页面访问
        if pageVisitId == event_id:
            err_c = interaction_attr.get('errorCount')
            if err_c and err_c['value'] > 0:
                visit_page_err_count += 1

            is_blank = interaction_attr.get('isBlank')
            if is_blank and is_blank['value'] == 'True':
                is_blank_page_count += 1

        # 点击事件
        elif elementClickId == event_id:
            err_c = interaction_attr.get('errorCount')
            if err_c and err_c['value'] > 0:
                element_click_err_count += 1

            repeat_click = interaction_attr.get('repeatClick')
            if repeat_click and repeat_click['value'] == 'True':
                repeat_click_count += 0

    # 收集扣分因素
    if visit_page_err_count > 0:
        penalty_reason.append("page_access_err")

    if is_blank_page_count > 0:
        penalty_reason.append("page_lose")

    if element_click_err_count > 1:
        penalty_reason.append("click_lapse")

    if time_since_page_load_dire['low_count'] > 2:
        penalty_reason.append("slow_loading")

    return penalty_reason


# 性能因素问题描述
def performance_problem_analysis(performance_all_attr_datas):

    if performance_all_attr_datas is None:
        return []

    # 扣分因素
    penalty_reason = []

    # 记录错误次数
    # 页面加载控制台报错
    page_loading_err_count = 0
    # 点击事件失效 >= 1.9
    click_latency_count = 0
    # 网络反馈慢
    delayed_net_work_count = 0

    for per_attr in performance_all_attr_datas:
        console_err = per_attr.get('consoleErrors')
        if console_err and console_err.get('value') > 0:
            page_loading_err_count += 1

        feed_back_interval = per_attr.get('feedbackInterval')
        if feed_back_interval:
            click_latency = feed_back_interval.get('displayName')
            value = feed_back_interval.get('value')
            if click_latency == "Click Latency" and value >= 1.9:
                click_latency_count += 1

        delayed_net_work = per_attr.get('slowNeChinaork')
        if delayed_net_work and delayed_net_work.get('value') == 'True':
            delayed_net_work_count += 1

    # 收集扣分因素
    if page_loading_err_count > 1:
        penalty_reason.append("page_loading_err")

    if click_latency_count > 0:
        penalty_reason.append("click_latency")

    if delayed_net_work_count > 0:
        penalty_reason.append("delayed_net_work")

    return penalty_reason


# 扣分逻辑
def apply_penalty(penalty_reason, res=None):
    if res is None:
        res = {
            'score': 100,
            'problem_list': []
        }

    # 事件权重
    visit_err_wei = 0.4  # 访问页面错误权重
    click_err_wei = 0.3  # 点击事件错误权重
    page_load_low_wei = 0.2  # 页面响应慢权重
    page_load_err = 0.1  # 网页加载报错权重

    # 基础权分
    base_penalty_score = 10

    if penalty_reason:
        for reason_list in penalty_reason:
            for reason in reason_list:
                if reason == 'page_access_err' or reason == 'page_loading_err':
                    # TODO 扣分
                    res['score'] -= (base_penalty_score * visit_err_wei)
                    res['problem_list'].append("页面加载报错")
                elif reason == 'page_lose':
                    res['score'] -= (base_penalty_score * visit_err_wei)
                    res['problem_list'].append("页面加载白屏")
                elif reason == 'click_lapse':
                    res['score'] -= (base_penalty_score * click_err_wei)
                    res['problem_list'].append("点击报错")
                elif reason == 'click_latency':
                    res['score'] -= (base_penalty_score * click_err_wei)
                    res['problem_list'].append("点击无响应")
                elif reason == 'slow_loading':
                    res['score'] -= (base_penalty_score * page_load_low_wei)
                    res['problem_list'].append("页面打开慢")
                elif reason == 'loading_err':
                    res['score'] -= (base_penalty_score * page_load_err)
                    res['problem_list'].append("页面加载报错")
                elif reason == 'delayed_net_work':
                    res['score'] -= (base_penalty_score * page_load_err)
                    res['problem_list'].append("网络反馈慢")

    return res


# 网站体验核心评分算法
def calculate_user_experience_score(interaction_all_attr_datas, performance_attr_datas):

    # 总扣分逻辑
    all_penalty_reason = []

    # 获取交互扣分因素
    interation_penalty_reasons = interation_problem_analysis(interaction_all_attr_datas)
    # 获取性能扣分因素
    performance_penalty_reasons = performance_problem_analysis(performance_attr_datas)
    all_penalty_reason.append(interation_penalty_reasons)
    all_penalty_reason.append(performance_penalty_reasons)

    return apply_penalty(all_penalty_reason)


# 接收评分数据并应用扣分
@app.route('/evaluate-user-experience', methods=['POST'])
def evaluate_user_experience():
    data = request.json
    print(data)
    interaction_all_attrs = []
    performance_attrs = []
    if data:
        for item in data:
            print(f"'desc': {item['desc']}")
            if 'interactionAttr' in item and 'eventTypeId' in item:
                event_type_id = item['eventTypeId']
                interaction_attr = item['interactionAttr']
                interaction_event = {}  # 创建用于存储交互事件的空字典
                if event_type_id and interaction_attr:
                    interaction_event['event_id'] = event_type_id
                    interaction_event['interaction_attr'] = interaction_attr
                    # 将字典加入 interaction_attrs 数组中
                    interaction_all_attrs.append(interaction_event)

            if 'performanceAttr' in item:
                performance_attr = item['performanceAttr']
                performance_attrs.append(performance_attr)
    else:
        res = {
            'code': '400',
            'msg': '文件无数据！',
            'data': None
        }
        return jsonify(res)

    # 调用核心算法函数
    res = calculate_user_experience_score(interaction_all_attrs, performance_attrs)

    return jsonify(res)


# 主入口
if __name__ == '__main__':
    app.run(port=6000)
